home *** CD-ROM | disk | FTP | other *** search
- Path: ub239.dialup.uwa.edu.au!localhost!prye
- From: prye@ub239.dialup.uwa.edu.au (Peter Rye)
- Newsgroups: comp.lang.c
- Subject: Re: [Help] I can't find my error.
- Date: 22 Feb 1996 14:47:59 GMT
- Organization: The University of Western Australia
- Message-ID: <PRYE.96Feb22224759@ub239.dialup.uwa.edu.au>
- References: <4ggvgr$1b2@aurora.engr.LaTech.edu>
- NNTP-Posting-Host: ub239.dialup.uwa.edu.au
- In-reply-to: pluu@engr.LaTech.edu's message of 22 Feb 1996 05:38:35 GMT
-
- >>>>> "PL" == PL <pluu@engr.LaTech.edu> writes:
-
- PL> Hi, all; Could anyone please tell me why the following program
- PL> won't work?
-
-
- PL> /* This program will ask your name and age; and then will print
- PL> your name and age for next year back */
-
- PL> #include <stdio.h>
-
- PL> main() { char name;
- PL> int age, next_age;
-
- PL> printf("%s\n","Please enter your name and age: ");
- PL> scanf("%s%d\n", &name, &age);
- PL> next_age= age + 1;
- PL> printf("Hi, %s ,next year, you will be %d\n", name, next_age);
- PL> }
-
- Hi PL,
-
- Have a look at this.
- scanf is notorious for being difficult to use for parsing user input.
- This is discussed in considerable detail in the FAQ (Section 12).
- You will see much advice about getting user input using fgets, and then
- parsing the string obtained with sscanf if you read a few of the messages
- here (also in the FAQ in the same section).
-
- A couple of other points are that you only declared name to be a single
- char.....probably not what you wanted. If the user enters his/her full
- name it will obviously considerably longer and not fit into the allocated
- storage. I have arbitrarily chosen an array size of 64 here. Since name is
- an array, it will be passed to sscanf as a pointer to the array and does
- not need the preceding ampersand.
-
- /* This program will ask your name and age; and then
- will print your name and age for next year back */
-
- #include <stdio.h>
- #include <stdlib.h>
-
- int main()
- {
- char name[64]; /* you need storage for name */
- char answer[64];
- int age, next_age, converted;
-
- printf("Please enter your name and age: \n");
- fgets(answer, 64, stdin);
-
- converted = sscanf(answer,"%s%d\n", name, &age);
-
- if (converted != 2) { /* if scanf fails to convert 2 */
- puts("Bad input"); /* variables on input, assume */
- exit(1); /* bad input and exit with error */
- }
-
- next_age= age + 1;
- printf("Hi, %s ,next year, you will be %d\n", name, next_age);
-
- return 0; /* main returns an int */
- }
-
- Hope this is of some help,
-
- Peter Rye
-
-
- --
- | Peter Rye Smoking areas in restaurants |
- | Respiratory Research Fellow are like peeing areas in |
- | Princess Margaret Hospital for Children swimming pools. |
- | Perth, Western Australia |
-